package com.tensquare.spit.controller;

import com.tensquare.spit.Pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@CrossOrigin
@RequestMapping("/spit")
public class SpitController {

    @Autowired
    private SpitService spitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;


    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){

        return  new Result(true, StatusCode.OK,"查询全部成功",spitService.findAll());
    }


    @RequestMapping(value="/{spitId}" ,method = RequestMethod.GET)
    public Result findAll(@PathVariable String spitId){
        return  new Result(true, StatusCode.OK,"Id查询成功",spitService.findById(spitId));
    }


    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Spit spit){
        String token=(String) request.getAttribute("claims_user");
        if (token==null || "".equals(token)){
            return new Result(false,StatusCode.ERROR,"权限不足！");
        }
        spitService.save(spit);
        return  new Result(true, StatusCode.OK,"添加成功");
    }

   @RequestMapping(value = "/{spitId}",method = RequestMethod.DELETE)
    public Result deleteByid(@PathVariable String spitId){
        spitService.deleteByid(spitId);
        return  new Result(true, StatusCode.OK,"删除成功");
    }

    @RequestMapping(value = "/{spitId}", method = RequestMethod.PUT)
    public Result update(@PathVariable String spitId,@RequestBody Spit spit) {
        spit.set_id(spitId);
        spitService.update(spit);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @RequestMapping(value = "/comment/{parentid}/{page}/{size}", method = RequestMethod.GET)
    public Result findByparentid(@PathVariable String parentid,@PathVariable int page,@PathVariable int size) {
        return new Result(true, StatusCode.OK, "根据父级id进行查询分页",spitService.findByparentid(parentid,page,size));
    }

    @RequestMapping(value = "/thumbup/{spitId}", method = RequestMethod.PUT)
    public Result thumbup (@PathVariable String spitId) {
        System.out.println(spitId);
        //判断当前用户是否已点赞但是前期要做验证

        //判断当前用户是否已点赞
       if(redisTemplate.opsForValue().get("thumbup_" + spitId)!=null){
           return new Result(false,StatusCode.ERROR,"不能重复点赞");
       }
        spitService.thumbup(spitId);
       redisTemplate.opsForValue().set("thumbup_"+spitId,1);
        return new Result(true, StatusCode.OK, "点赞成功");

    }




}
